package socket.udp.multServer;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Arrays;
import java.util.Random;
import java.util.UUID;

/**
 * @description: 类描述
 * @author: Fesine
 * @createTime:2016/10/8 15:25
 * @update:修改内容
 * @author: Fesine
 * @updateTime:2016/10/8 15:25
 */
public class ClientThread implements Runnable {

    private Random random = new Random();
    private String uuid = UUID.randomUUID().toString();
    private DatagramSocket datagramSocket = null;
    public void run() {
        try {
            init();
            byte[] buffer = new byte[1024 * 64];
            byte[] btSend = new byte[]{(byte) random.nextInt(127), (byte) random.nextInt(127),
                    (byte) random.nextInt(127)};
            DatagramPacket packet = new DatagramPacket(buffer, buffer.length, InetAddress.getByName
                    ("localhost"), 2233);
            packet.setData(btSend);
            System.out.println(uuid + ": 发送:" + Arrays.toString(btSend));
            sendData(packet);
            receive(packet);
            byte[] bt = new byte[packet.getLength()];
            //将packet的字节数据复制到新的字节数据组
            System.arraycopy(packet.getData(), 0, bt, 0, packet.getLength());
            if (null != bt && bt.length > 0) {
                System.out.println(uuid + ": 收到:" + Arrays.toString(bt));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void init() throws SocketException {

        try {
            datagramSocket = new DatagramSocket(random.nextInt(9999));
            datagramSocket.setSoTimeout(10 * 1000);
            System.out.println("客户端启动成功");
        } catch (Exception e) {
            datagramSocket = null;
            System.out.println("客户端启动失败");
            e.printStackTrace();
        }
    }

    public void receive(DatagramPacket packet) throws Exception{
        try {
            datagramSocket.receive(packet);
        } catch (IOException e) {
            throw e;
        }
    }

    public void sendData(DatagramPacket packet){
        try {
            datagramSocket.send(packet);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
